package com.ftw.commons.utils.inputfilter

import android.text.InputFilter
import android.text.Spanned
import java.util.regex.Pattern

class SizeFilterWithTextAndLetter(private var letterMaxLength: Int) : InputFilter {

    private val chinesePattern = Pattern.compile("[\u4e00-\u9fa5]+")


    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence? {

        val isAdd = dstart == dend
        if (!isAdd) {//删除文字不限制
            return null
        }

        val originLength = calculateLength(dest!!)

        val isChinese = chinesePattern.matcher(source.toString()).find()
        if (isChinese) {
            return when {
                originLength >= letterMaxLength -> ""
                originLength + source!!.length * 2 > letterMaxLength -> {
                    var length = (letterMaxLength - originLength + 1) / 2
                    if (length < 0) length = 0
                    source.subSequence(0, length)
                }
                else -> null
            }
        } else {
            return when {
                originLength >= letterMaxLength -> ""
                originLength + source!!.length > letterMaxLength -> {
                    letterMaxLength = source.length
                    val length = letterMaxLength
                    source.subSequence(0, length)
                }
                else -> null
            }
        }

        return ""

    }


    /**
     * 计算原有文本占据的长度
     *
     * @param dest 原文本
     * @return 总长度
     */
    private fun calculateLength(dest: Spanned): Int {
        var chineseLength = 0
        var letterLength = 0
        for (i in dest.indices) {
            if (chinesePattern.matcher(dest.subSequence(i, i + 1)).find()) {
                chineseLength += 2
            } else {
                letterLength += 1
            }
        }
        return chineseLength + letterLength
    }



}